﻿#include "udputils.h"

UDPUtils::UDPUtils(const QString& clientAddr,  //
                   const int& clientPort,      //
                   const bool& isShowChinese, QObject* parent)
    : QObject(parent) {
  client_addr = clientAddr;
  client_port = clientPort;
  // server_addr     = serverAddr;
  is_show_chinese = isShowChinese;
}

UDPUtils::~UDPUtils() { closeUDP(); }

void UDPUtils::sltOpenUDP() {
  /****************************** 获取本机IP信息 *****************************************/

  /*  QString localHostName = QHostInfo::localHostName();

    qDebug() << "localHostName:" << localHostName;
    QHostInfo info = QHostInfo::fromName( localHostName );
    foreach ( QHostAddress address, info.addresses() ) {
        if ( address.protocol() == QAbstractSocket::IPv4Protocol ) { qDebug() << "IPv4:" << address.toString(); }
    }*/
  /****************************** UDP网络 *************************************************/
  udpsocket = new QUdpSocket(this);
  // 绑定本机接收数据的地址和端口号
  QHostAddress address(client_addr);
  if (udpsocket->bind(address, static_cast<quint16>(client_port))) {
    openOk = true;

    connect(udpsocket, SIGNAL(readyRead()), this, SLOT(sltReceiveData()));

    emit sigSendTips("无", QString("正确，UDP绑定地址[%1 %2] 成功").arg(client_addr).arg(client_port));
  } else {
    emit sigSendTips("无", QString("错误，UDP绑定地址[%1 %2] 失败").arg(client_addr).arg(client_port));
  }
}

void UDPUtils::closeUDP() { udpsocket->close(); }

void UDPUtils::sltReceiveData() {
  while (udpsocket->hasPendingDatagrams()) {  //拥有等待的数据报
    QHostAddress receivAddress;
    QByteArray datagram;  //用于存放接收的数据报
    //让datagram的大小为等待处理的数据报的大小，这样才能接收到完整的数据
    datagram.resize(static_cast<int>(udpsocket->pendingDatagramSize()));
    //接收数据报，将其存放到datagram中
    udpsocket->readDatagram(datagram.data(), datagram.size(), &receivAddress);
    // UPDATE 2022.07.28 udp改成可以接收多个调度信息，将收到的ip显示出来
    //        if ( receivAddress.toString() != server_addr )  //排除非指定ip以外的消息
    //        {
    //            return;
    //        }
    if (is_show_chinese) {
      QTextCodec* tc = QTextCodec::codecForName("GBK");
      QString dataStr = tc->toUnicode(datagram);
      emit sigSendTips(receivAddress.toString(), dataStr);
    } else {
      //将数据进行解析处理
      emit sigReceiveData(receivAddress.toString(), datagram);
    }
  }
}

void UDPUtils::sendData(QString ip, int port, QByteArray data) {
  // udp连接成功前，不发送信息
  if (!openOk) { return; }
  QHostAddress address(ip);
  udpsocket->writeDatagram(data, address, static_cast<quint16>(port));  // 指定IP和端口通过UDP协议发送
}
